package org.liukai.tutorial.controller;

import org.apache.log4j.Logger;
import org.liukai.tutorial.domain.Authority;
import org.liukai.tutorial.domain.Role;
import org.liukai.tutorial.service.IAccountService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 角色
 * 
 * @author liukai
 * 
 */
@Controller
@RequestMapping("/account/role")
public class RoleAction {

	protected static Logger logger = Logger.getLogger("controller");

	@Resource(name = "accountService")
	private IAccountService service;

	// 重定向至Role列表
	private final String ROLE_LIST = "redirect:/account/role";

	/**
	 * 获得所有的Authority列表返回到页面.
	 */
	@ModelAttribute("authList")
	public List<Authority> getAllAuthority() {
		return service.getAllAuthority();
	}

	/**
	 * 获得所有的Role并传递至role page
	 */
	@RequestMapping("")
	public String getAllRole(Model model) {
		model.addAttribute("roleList", service.getAllRole());
		return "role";
	}

	/**
	 * 初始化一个Role至addRole页面
	 */
	@RequestMapping(value = "/save")
	public String getAddRole(Model model) {
		model.addAttribute("roleAttribute", new Role());
		return "addRole";
	}

	/**
	 * 新增Role
	 */
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public ModelAndView addRole(@ModelAttribute("roleAttribute") Role role) {
		service.addRole(role);
		return new ModelAndView(ROLE_LIST);
	}

	@RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
	public ModelAndView deleteRole(@PathVariable(value = "id") Integer id) {
		service.deleteRole(id);
		return new ModelAndView(ROLE_LIST);
	}

	/**
	 * 根据roleId获得对应的Role信息传至editRole page
	 */
	@RequestMapping(value = "/edit/{id}")
	public String getEditRole(@PathVariable(value = "id") Integer id,
			Model model) {

		Role role = service.getRoleById(id);

		Map<Integer, Integer> map = new HashMap<Integer, Integer>();

		for (int i = 0; i < role.getAuthIds().size(); i++) {
			map.put(role.getAuthIds().get(i), role.getAuthIds().get(i));
		}
		role.setAuthCheckBox(map);

		model.addAttribute("roleAttribute", role);

		return "editRole";
	}

	/**
	 * 修改Role
	 */
	@RequestMapping(value = "/edit/{id}", method = RequestMethod.POST)
	public ModelAndView editRole(@ModelAttribute("roleAttribute") Role role,
			@PathVariable(value = "id") Integer id) {

		role.setId(id);

		service.updateRole(role);

		return new ModelAndView(ROLE_LIST);

	}

}
